package a04_字符串;

import java.util.Arrays;


/**
 * <p>
 * a04_反转字符串中的单词
 * </p>
 *
 * @author flyduck
 * @since 2024-07-10
 */
public class a04_反转字符串中的单词复习1 {
    public static String reverseWords(String s) {
        char[] oldArray = s.toCharArray();
        //1、去除首尾以及中间得空格
        char[] newArray = removeExtraSpaces(oldArray);
        //2、反转整个字符串
        reverse(newArray,0,newArray.length - 1);
        //3、反转字符串里面的单词
        reverseEachWord(newArray);

        return new String(newArray);

    }

    private static void reverseEachWord(char[] newArray) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex <= newArray.length; fastIndex++) {
            if(fastIndex == newArray.length || newArray[fastIndex] == ' '){
                reverse(newArray, slowIndex, fastIndex - 1);
                slowIndex = fastIndex + 1;
            }
        }
    }

    private static void reverse(char[] newArray, int leftIndex, int rightIndex) {
        while (leftIndex < rightIndex) {
            char temp = newArray[leftIndex];
            newArray[leftIndex] = newArray[rightIndex];
            newArray[rightIndex] = temp;

            leftIndex++;
            rightIndex--;
        }
    }


    public static char[] removeExtraSpaces(char[] oldArray){
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < oldArray.length; fastIndex++) {
            if(oldArray[fastIndex] != ' '){//开始新的一个单词了
                if(slowIndex != 0){//如果slowIndex不是第一个单词，那么需要加一个空格
                    oldArray[slowIndex] = ' ';
                    slowIndex++;
                }
                while (fastIndex < oldArray.length && oldArray[fastIndex] != ' ') {
                    oldArray[slowIndex] = oldArray[fastIndex];
                    slowIndex++;
                    fastIndex++;
                }
            }
        }
        return Arrays.copyOfRange(oldArray, 0, slowIndex);
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("a good   example"));
    }
}
